﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.OrmLite;
using ServiceStack.DataAnnotations;

namespace LCRReader
{
    public class TestConfig
    {
        [PrimaryKey, AutoIncrement]
        public int ID { get; set; }
        public string Name { get; set; }
        public float Upper { get; set; }
        public float Lower { get; set; }
        public float Value { get; set; }
        public bool Enable { get; set; }
        public string CMD { get; set; }
        public int Result { get; set; }
    }

    public class TestConfigAccess
    {
        static string _path = "";
        static System.Data.IDbConnection _db = null;
        public TestConfigAccess(string path = "./config/cfg.db")
        {
            if (path != _path)
            {
                _path = path;
                if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(path)))
                {
                    System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path));
                }
                OrmLiteConnectionFactory con = new OrmLiteConnectionFactory(path, SqliteDialect.Provider);
                
                _db = con.Open();
                if (!_db.TableExists<TestConfig>())
                {
                    _db.DropAndCreateTable<TestConfig>();
                }
            }
        }

        public int DeleteByName(string Name)
        {
            return _db.Delete<TestConfig>(t => t.Name == Name);
        }

        public int DeleteById (int id)
        {
            return _db.Delete<TestConfig>(t => t.ID == id);
        }

        public long Insert(TestConfig testConfig)
        {
            return _db.Insert(testConfig);
        }

        public int Update(TestConfig testConfig,int ID)
        {
            testConfig.ID = ID;
            return _db.Update(testConfig,p=>p.ID==ID);
        }

        public List<TestConfig> GetAll()
        {
            return _db.Select<TestConfig>();
        }
        public int UpdateEnable(int ID,bool enable)
        {
            return _db.Update<TestConfig>(new { Enable = enable }, p => p.ID == ID);
        }

        public int UpdateValueResult(int ID, float value, int result)
        {
            return _db.Update<TestConfig>(new { Value = value, Result = result }, p => p.ID == ID);
        }

    }
}
